package com.sss.myspringsecurity.config.securityconfig.filter;

import com.alibaba.fastjson.JSON;
import com.sss.myspringsecurity.util.*;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Token 验证
 * @author sss
 * @date 2020-02-09 19:53
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authorToken = request.getHeader("AuthorToken");
        if (!StringUtils.isEmpty(authorToken) && StringUtils.isEmpty(SecurityUtils.getAuthentication()))
        {
            Map<String, Object> map;
            try {
                map = JwtUtil.paresToken(authorToken);
            } catch (ExpiredJwtException e) {
                ServletUtils.renderString(response, JSON.toJSONString(Result.fail(ResponseDataEnum.TOKEN_EXPIRED)));
                return;
            }

            String userName = (String) map.get("username");
            UserDetails details=null;
            if (!StringUtils.isEmpty(userName)) {
               details = userDetailsService.loadUserByUsername(userName);
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(details, null, details.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }


}
